package ConnectionTest;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpServer {
    private ServerSocket socket = null;

    private ExecutorService service = Executors.newCachedThreadPool();

    public TcpServer(int port) throws IOException {
        socket = new ServerSocket(9090);
    }

    public void start() throws IOException {
        System.out.println("服务端启动！");

        while (true){
            Socket clientSocket = socket.accept();

            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

        }
        //获取来的连接

    }

    public void processConnection(Socket clientSocket) throws IOException {
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            while(true){
                Scanner scannerClient = new Scanner(inputStream);
                String request = scannerClient.next();

                String response = process(request);

                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(response);
                writer.flush();

                System.out.printf("[%s:%d] req:%s, resp:%s\n", clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(), request, response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            clientSocket.close();
        }
    }

    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpServer server = new TcpServer(9090);
        server.start();
    }
}
